package com.qyhl.party.party.supplement;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.Postcard;
import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.facade.callback.NavCallback;
import com.alibaba.android.arouter.launcher.ARouter;
import com.gyf.immersionbar.ImmersionBar;
import com.qyhl.party.R;
import com.qyhl.party.R2;
import com.qyhl.webtv.basiclib.base.BaseActivity;
import com.qyhl.webtv.basiclib.base.BaseIViewPresenter;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.basiclib.utils.dialog.OtherDialog;
import com.qyhl.webtv.commonlib.common.CommonUtils;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.entity.party.PartyLoginBean;
import com.qyhl.webtv.commonlib.entity.party.PartyUserInfo;
import com.qyhl.webtv.commonlib.entity.party.PartyZoneBean;
import com.qyhl.webtv.commonlib.utils.view.CustomKeyboardEditText;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import butterknife.BindView;
import butterknife.OnClick;

@Route(path = ARouterPathConstant.PARTY_SUPPLEMENT)
public class PartySupplementActivity extends BaseActivity implements PartySupplementContract.PartySupplementView {
    @BindView(R2.id.name)
    EditText name;
    @BindView(R2.id.identity)
    CustomKeyboardEditText identity;
    @BindView(R2.id.phone)
    EditText phone;
    @BindView(R2.id.code)
    EditText code;
    @BindView(R2.id.code_btn)
    TextView codeBtn;
    @BindView(R2.id.face_group)
    RadioGroup faceGroup;
    @BindView(R2.id.department)
    TextView department;
    @BindView(R2.id.job_group)
    RadioGroup jobGroup;
    @BindView(R2.id.zone)
    TextView zone;
    @BindView(R2.id.code_layout)
    LinearLayout codeLayout;

    @Autowired(name = "token")
    String token;
    @Autowired(name = "bean")
    PartyUserInfo mBean;
    @Autowired(name = "isEdit")
    boolean isEdit;

    private String upPhone, upCode, upFace;

    private int upDepId, upZoneId;

    private int isWork = -1;

    private static final int REQUEST_CODE = 100;

    private CountDownTimer mTimer;

    private PartySupplementPresenter mPresenter;

    private OtherDialog.Builder builder;

    private CommonAdapter<PartyZoneBean> townAdapter;
    private CommonAdapter<PartyZoneBean> communityAdapter;

    private List<PartyZoneBean> townList = new ArrayList<>();
    private List<PartyZoneBean> communityList = new ArrayList<>();

    private int index = 0;

    @Override
    protected int getContentView() {
        return R.layout.party_activity_supplement;
    }

    @Override
    protected void setImmersionBar(ImmersionBar mImmersionBar) {
        setDefaultImmerBar();
    }

    @Override
    protected BaseIViewPresenter initBaseIViewPresenter() {
        return null;
    }

    @Override
    protected void init() {
        mPresenter = new PartySupplementPresenter(this);

        upPhone = CommonUtils.getInstance().getUserName();
        phone.setText(upPhone);

        mPresenter.getZoneList();
        if (isEdit) {
            codeLayout.setVisibility(View.GONE);

            name.setText(mBean.getName());

            identity.setText(mBean.getCard());

            upFace = mBean.getPolFace();
            switch (upFace) {
                case "PARTY_MEMBER":
                    faceGroup.check(R.id.member);
                    break;
                case "LEAGUE_MEMBER":
                    faceGroup.check(R.id.league);
                    break;
                case "MASSES":
                    faceGroup.check(R.id.masses);
                    break;
            }

            if (mBean.getDep() != null) {
                department.setText(mBean.getDep().getName());
                upDepId = mBean.getDep().getId();

                isWork = mBean.getIsWork();
                if (isWork == 0) {
                    jobGroup.check(R.id.job_off);
                } else {
                    jobGroup.check(R.id.job_on);
                }
            }

            zone.setText(mBean.getZone().getName());

            upZoneId = mBean.getZone().getId();
        } else {
            codeLayout.setVisibility(View.VISIBLE);
        }
    }

    @Override
    protected void setListener() {
        //配置计时器
        mTimer = new CountDownTimer(60000, 1000) {
            @SuppressLint("SetTextI18n")
            @Override
            public void onTick(long millisUntilFinished) {
                codeBtn.setText(millisUntilFinished / 1000 + "s后重新获取");
            }

            @Override
            public void onFinish() {
                resetCodeBtn();
            }
        };

        faceGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == R.id.member) {
                    upFace = "PARTY_MEMBER";
                } else if (checkedId == R.id.league) {
                    upFace = "LEAGUE_MEMBER";
                } else {
                    upFace = "MASSES";
                }
            }
        });

        jobGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == R.id.job_on) {
                    isWork = 1;
                } else {
                    isWork = 0;
                }
            }
        });
    }

    private void resetCodeBtn() {
        if (mTimer != null) {
            mTimer.cancel();
        }
        codeBtn.setText("获取验证码");
        codeBtn.setEnabled(true);
    }

    private void checkData() {
        if (!CommonUtils.getInstance().getUserCheck().equals("1") && CommonUtils.getInstance().getSite() == 217) {
            showToast("用户信息审核中，暂时无法使用该功能！", INFO);
            return;
        }

        String upName = name.getText().toString();
        if (TextUtils.isEmpty(upName)) {
            dismissLoading();
            showToast("请填写真实姓名！");
            return;
        }

        String upCard = identity.getText().toString();
        if (!StringUtils.isIdentityNum(upCard)) {
            dismissLoading();
            showToast("请填写正确的身份证号码！");
            return;
        }

        if (!isEdit) {
            upCode = code.getText().toString();
            if (TextUtils.isEmpty(upCode)) {
                dismissLoading();
                showToast("请填写验证码！");
                return;
            }
        }

        if (TextUtils.isEmpty(upFace)) {
            dismissLoading();
            showToast("请选择政治面貌！");
            return;
        }

        if (upDepId != 0) {
            if (isWork == -1) {
                dismissLoading();
                showToast("请选择是否在职！");
                return;
            }
        } else {
            isWork = 0;
        }

        if (upZoneId == 0 || StringUtils.isEmpty(zone.getText().toString())) {
            dismissLoading();
            showToast("请选择所在区域！");
            return;
        }

        if (isEdit) {
            mPresenter.change(upPhone, upName, token, upCard, upZoneId, upDepId, upFace, isWork);
        } else {
            mPresenter.register(upPhone, upName, upCode, upCard, upZoneId, upDepId, upFace, isWork);
        }
    }

    @OnClick({R2.id.back_btn, R2.id.commit_btn, R2.id.code_btn, R2.id.department, R2.id.zone})
    public void onClick(View view) {
        int viewId = view.getId();
        if (viewId == R.id.back_btn) {
            finish();
        } else if (viewId == R.id.commit_btn) {
            showLoading();
            checkData();
        } else if (viewId == R.id.code_btn) {
            mTimer.start();
            codeBtn.setEnabled(false);
            mPresenter.getCode(upPhone);
        } else if (viewId == R.id.department) {
            ARouter.getInstance()
                    .build(ARouterPathConstant.PARTY_SUPPLEMENT_DEPARTMENT)
                    .withInt("depId", upDepId)
                    .navigation(this, REQUEST_CODE);
        } else if (viewId == R.id.zone) {
            if (townList.size() > 0) {
                if (builder == null) {
                    builder = new OtherDialog.Builder(PartySupplementActivity.this)
                            .setContentView(R.layout.party_dialog_zone)
                            .setGravity(Gravity.BOTTOM)
                            .setWidth(1.0f)
                            .setCanceledOnTouchOutside(true)
                            .setCancelable(true);

                    RecyclerView townRecycler = builder.getView().findViewById(R.id.town_recycler);
                    RecyclerView communityRecycler = builder.getView().findViewById(R.id.community_recycler);

                    DividerItemDecoration divider = new DividerItemDecoration(this, DividerItemDecoration.VERTICAL);
                    divider.setDrawable(Objects.requireNonNull(ContextCompat.getDrawable(this, R.drawable.party_study_item_divider)));

                    townRecycler.setLayoutManager(new LinearLayoutManager(this));
                    townRecycler.addItemDecoration(divider);

                    communityRecycler.setLayoutManager(new LinearLayoutManager(this));
                    communityRecycler.addItemDecoration(divider);

                    townRecycler.setAdapter(townAdapter = new CommonAdapter<PartyZoneBean>(this, R.layout.party_item_supplement_zone, townList) {
                        @Override
                        protected void convert(ViewHolder holder, PartyZoneBean partyZoneBean, int position) {
                            holder.setText(R.id.name, partyZoneBean.getName());

                            if (partyZoneBean.isSelected()) {
                                holder.setTextColorRes(R.id.name, R.color.party_common_red);
                            } else {
                                holder.setTextColorRes(R.id.name, R.color.party_common_title);
                            }
                        }
                    });

                    communityRecycler.setAdapter(communityAdapter = new CommonAdapter<PartyZoneBean>(this, R.layout.party_item_supplement_zone, communityList) {
                        @Override
                        protected void convert(ViewHolder holder, PartyZoneBean partyZoneBean, int position) {
                            holder.setText(R.id.name, partyZoneBean.getName());

                            if (partyZoneBean.isSelected()) {
                                holder.setTextColorRes(R.id.name, R.color.party_common_red);
                            } else {
                                holder.setTextColorRes(R.id.name, R.color.party_common_title);
                            }
                        }
                    });

                    townAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
                        @Override
                        public void onItemClick(View view, RecyclerView.ViewHolder viewHolder, int position) {
                            index = position;
                            for (int i = 0; i < townList.size(); i++) {
                                townList.get(i).setSelected(i == position);
                            }


                            communityList.clear();
                            communityList.addAll(townList.get(position).getChildren());
                            communityAdapter.notifyDataSetChanged();
                            townAdapter.notifyDataSetChanged();
                        }

                        @Override
                        public boolean onItemLongClick(View view, RecyclerView.ViewHolder viewHolder, int i) {
                            return false;
                        }
                    });

                    communityAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
                        @Override
                        public void onItemClick(View view, RecyclerView.ViewHolder viewHolder, int position) {
                            for (int i = 0; i < communityList.size(); i++) {
                                communityList.get(i).setSelected(i == position);
                            }

                            for (int i = 0; i < townList.get(index).getChildren().size(); i++) {
                                townList.get(index).getChildren().get(i).setSelected(i == position);
                            }

                            communityAdapter.notifyDataSetChanged();

                            zone.setText(communityList.get(position).getName());
                            upZoneId = communityList.get(position).getId();
                            builder.dismiss();
                        }

                        @Override
                        public boolean onItemLongClick(View view, RecyclerView.ViewHolder viewHolder, int i) {
                            return false;
                        }
                    });
                }

                builder.show();
            } else {
                showLoading("获取中");
                mPresenter.getZoneList();
            }

        }
    }

    @Override
    public void setCode(String msg) {
        showToast(msg);
    }

    @Override
    public void registerSuccess(PartyLoginBean bean) {
        dismissLoading();

        if (isEdit) {
            showToast("修改成功!");
            setResult(RESULT_OK);
            finish();
        } else {
            showToast("补充成功!");
            ARouter.getInstance()
                    .build(ARouterPathConstant.PARTY_BUILDING_HOME)
                    .navigation(this, new NavCallback() {
                        @Override
                        public void onArrival(Postcard postcard) {
                            finish();
                        }
                    });
        }
    }

    @Override
    public void registerError(String msg) {
        dismissLoading();
        showToast(msg);
    }

    @Override
    public void setZoneList(List<PartyZoneBean> beanList) {
        dismissLoading();

        if (beanList != null && beanList.size() > 0) {
            townList.clear();
            townList.addAll(beanList.get(0).getChildren());
            townList.get(0).setSelected(true);

            communityList.clear();
            communityList.addAll(townList.get(0).getChildren());
            communityList.get(0).setSelected(true);
        }

    }

    @Override
    public void setZoneError(String msg) {
        dismissLoading();
        showToast(msg);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE) {
            if (data != null) {
                String name = data.getStringExtra("name");
                upDepId = data.getIntExtra("depId", 0);
                department.setText(name);
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mTimer != null) {
            mTimer.cancel();
            mTimer = null;
        }
    }
}
